import {
  apiUrl
} from "../../config/index.js";
import EventBus from '../../utils/EventBus'
// index.js
Page({
  data: {
    headImg: '/image/head.png', // 用户的头像URL，初始化为空或默认头像
    isLoggedIn: false, // 假设用户默认未登录
    nickname: '点击头像登录',
  },
  onLoad(options) {
    this.refreshUserInfo()
    EventBus.$on('refreshUserInfo', () => {
      this.refreshUserInfo(); // 刷新数据
    });
  },
  onUnload() {
    EventBus.$off('refreshUserInfo'); // 页面卸载时移除监听
  },
  refreshUserInfo() {
    let token = wx.getStorageSync('token')
    if (token) {
      this.setData({
        isLoggedIn: true
      })
    }
    let that = this
    wx.request({
      url: apiUrl + '/user/info',
      method: 'GET',
      header: {
        'sysToken': token
      },
      success: (res) => {
        if (res.data.code == 1) {
          that.setData({
            headImg: res.data.data.headImg,
            nickname: res.data.data.nickname
          })
        }

      },
      fail: (err) => {
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none',
        });
      }
    })
  },
  handleAvatarTap() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000,
      });
      // 这里可以添加跳转到登录页面的逻辑
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      // 如果已登录，可以处理其他逻辑，比如打开个人资料页面
    }
  },
  handleSetting() {
    let url = '/pages/settings/index?headImg=' + this.data.headImg + '&nickname=' + this.data.nickname
    console.log(url)
    wx.navigateTo({
      url: '/pages/settings/index?headImg=' + encodeURIComponent(this.data.headImg) + '&nickname=' + encodeURIComponent(this.data.nickname)
    })
  },
  handleAboutUs() {
    wx.navigateTo({
      url: '/pages/about/index',
    })
  },
  handleExit() {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: apiUrl + '/user/logout',
      method: 'GET',
      header: {
        'sysToken': token
      },
      success: (res) => {
        if (res.data.code == 1) {
          that.setData({
            headImg: '/image/head.png',
            nickname: '点击头像登录',
            isLoggedIn: false
          })
          wx.removeStorageSync('token')
        } else {
          wx.showToast({
            title: '退出登录失败',
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '退出登录失败',
          icon: 'none',
        });
      }
    })
  }
});